﻿
@inject IDataCacheService _dataCacheService
@inject IHttpService _httpService
@inject IPopupService PopupService


<MDialog @bind-Value="Dialog"
         Width="500">
    <MDCard>
        <MCardTitle Class="text-h5">
            选择收藏
        </MCardTitle>
        <MCardText>
            在下方选择收藏到的位置，可以选中多个
        </MCardText>
        <MCardText Class="pb-0">
            <div style="display:flex;">
                @foreach (var item in UserFavoriteInfor)
                {
                    <MCheckbox Value="SelectedItemIds.Contains( item.Id)" TValue="bool" ValueChanged="@((e) => { if (e) SelectedItemIds.Add(item.Id); else SelectedItemIds.RemoveAll(s => s == item.Id); })"
                               Label="@item.Name" Class="m-0 me-4"
                               HideDetails="true"/>
                }

            </div>

        </MCardText>


        <MCardActions>
            <MSpacer></MSpacer>
            <CnGalWebSite.Components.Buttons.MasaButton Text="收藏" IsAsync="true" OnClick="OnClickFavorited" Icon="mdi-heart" TextStyle />
        </MCardActions>
    </MDCard>
</MDialog>

@code {

    [Parameter]
    public EventCallback OnFavorited { get; set; }
    [Parameter]
    public long ObjectId { get; set; }
    [Parameter]
    public FavoriteObjectType Type { get; set; }


    public List<FavoriteFolderOverviewModel> UserFavoriteInfor { get; set; } = new List<FavoriteFolderOverviewModel>();


    List<long> SelectedItemIds = new List<long>();
    bool Dialog { get; set; }


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    public void Refresh(List< FavoriteFolderOverviewModel> userFavoriteInfor)
    {
        if (SelectedItemIds.Any())
        {
            SelectedItemIds.Clear();
        }
        UserFavoriteInfor = userFavoriteInfor;
        Dialog = true;
        StateHasChanged();
        
    }

    public async Task OnClickFavorited()
    {
        if (SelectedItemIds == null || SelectedItemIds.Any() == false)
        {
            await PopupService.ToastErrorAsync("请选择要保存到的收藏夹", "请选择要保存到的收藏夹");
            return;
        }
        try
        {
            var obj = await _httpService.PostAsync<AddFavoriteObjectViewModel, Result>("api/favorites/AddFavoriteObject", new AddFavoriteObjectViewModel { FavoriteFolderIds = SelectedItemIds?.ToArray() ?? new long[] { }, ObjectId = ObjectId, Type = Type });
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync("收藏失败", obj.Error);
                return;
            }
            else
            {
                Dialog = false;
                StateHasChanged();
                await OnFavorited.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "收藏失败");
            return;
        }
    }
}
